<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\library\Token;
use app\common\model\Area;
use app\common\model\Chat;
use app\common\model\ChatDetail;
use app\common\model\Config;
use app\common\model\OrderLog;
use app\common\model\Share;
use app\common\model\Something;
use app\common\model\UserMoneyLog;
use app\common\model\Wechat;
use app\common\service\AuctionBanner;
use app\common\service\AuctionCategory;
use app\common\service\AuctionGood;
use app\common\service\AuctionOrder;
use app\common\service\AuctionOrderTem;
use EasyWeChat\Foundation\Application;
use think\Db;
use think\Log;
use think\Session;
use think\Loader;

class Index extends Frontend
{

    protected $noNeedLogin = ['oauth_callback','test','task','timinggood'];
    protected $noNeedRight = ['*'];
    protected $layout = '';


    public function test(){


    }

    /**
     * 寻人寻物定时任务
     */
    public function task(){
        $data=Db::name('something')
            ->where(['status'=>3])
            ->select();

        $UserMoneyLogModel=new UserMoneyLog();
        Log::write('已进入定时任务','notice');
        if(!empty($data)){
            foreach ($data as $key=>$val){
                $thingData=Something::get($val['id']);
                $UserMoneyLogModel->gold($thingData->type,$thingData->publisherUserId,$thingData->receiverUserId,$thingData->money,$val['id']);

                $thingData->status=4;
                $thingData->save();
            }
        }


    }

    /**
     * 竞拍定时任务
     */
    public function timinggood(){
        $wechat =new Wechat();
        $UserMoneyLogModel=new UserMoneyLog();
        $data=Db::name('auction_good')->where(['status'=>1])->select();
        Log::write('竞拍已进入定时任务','notice');
        if(!empty($data)){
            foreach ($data as $key=>$val){
                if(($val['createtime']+(int)$val['hour']*360)<=time()){

                    $order=Db::name('auction_order')->order('createtime','desc')->where(['good_id'=>$val['id']])->find();

                    if(!empty($order)){
                        $updata['status']=2;
                        $updata['receiverUserId']=$order['user_id'];
                        Db::name('auction_good')->where(['id'=>$val['id']])->update($updata);

                        $thingData=\app\common\model\AuctionGood::get($val['id']);
                        $UserMoneyLogModel->bidgold($thingData->publisherUserId,$thingData->receiverUserId,$thingData->money,$val['id']);

                        $templateData=array();
                        $templateData['first']='恭喜！您发布的竞拍商品竞拍成功。';
                        $templateData['keyword1']=$val['name'];
                        $templateData['keyword2']=$val['money'];
                        $templateData['remark']='请联系获拍者给您提供收货信息，并把商品寄给获拍者。';
                        try{
                            $user=\app\admin\model\User::get($val['publisherUserId']);

                            $wechat->template('aw3Rka1hQmJhVtkJkfYC8EJ9LmpmzZ56P4LGVXC9Vl8',
                                url('index/auctiondetail',array('id'=>$order['good_id']),true,true),$templateData,$user->openid);
                        }catch (\Exception $e){

                        }


                        $templateData=array();
                        $templateData['first']='恭喜！您已竞拍成功。';
                        $templateData['keyword1']=$val['name'];
                        $templateData['keyword2']=$val['money'];
                        $templateData['remark']='请联系发布者发送你的收货信息.';
                        try{
                            $user=\app\admin\model\User::get($order['user_id']);

                            $wechat->template('aw3Rka1hQmJhVtkJkfYC8EJ9LmpmzZ56P4LGVXC9Vl8',
                                url('index/auctiondetail',array('id'=>$order['good_id']),true,true),$templateData,$user->openid);
                        }catch (\Exception $e){

                        }


                        $order_users=Db::name('auction_order')
                            ->distinct('user_id')
                            ->field('user_id')
                            ->order('createtime','desc')
                            ->where(['good_id'=>$val['id']])
                            ->column('user_id');

                        foreach ($order_users as $key=>$val){
                            if($val!=$order['user_id']){
                                $templateData=array();
                                $templateData['first']='很抱歉，您竞拍的商品竞拍失败';
                                $templateData['keyword1']=$val['name'];
                                $templateData['keyword2']='竞拍失败';
                                $templateData['keyword3']='失败原因：已有人超过您的叫价价格';
                                $templateData['remark']='很抱歉，您竞拍的xxx商品竞拍失败，保证金会在24小时内退还给您';
                                try{
                                    $user=\app\admin\model\User::get($val);

                                    $wechat->template('G7m5_rn49GYuRLYQsv9H1F9CAx0nqzD4yOUJLrQOpBg',
                                        url('index/auctiondetail',array('id'=>$order['good_id']),true,true),$templateData,$user->openid);
                                }catch (\Exception $e){

                                }
                            }

                        }
                    }else{
                        $templateData=array();
                        $templateData['keyword1']=$val['name'];
                        $templateData['keyword2']='项目流拍';
                        $templateData['keyword3']=date('Y-m-d H:i:s',time());
                        $templateData['remark']='如有疑问，请联系客服处理。';
                        try{
                            $user=\app\admin\model\User::get($val['publisherUserId']);
                            $wechat->template('86uxWC2vjPhS1D8x_IMRC7S0jDQ1asJd_p1S5spLw0s',
                                url('index/auctiondetail',array('id'=>$order['good_id']),true,true),$templateData,$user->openid);
                        }catch (\Exception $e){

                        }

                        Db::name('auction_good')->where(['id'=>$val['id']])->update(['status'=>3]);
                    }

                }
            }
        }

    }




    /**
     * 首页
     */
    public function index()
    {
        $somethingModel=new Something();

        $TypeName=$this->request->param('Type');



        if($this->request->isAjax()){

            $RequestName=$this->request->post('RequestName');
            if($RequestName=='share'){
                $something_id=$this->request->post('something_id');
                $user=$this->auth->getUser();
                $shareModel=new Share();
                $UpdataWhere['user_id']=array('eq',$user->id);
                $UpdataWhere['something_id']=array('eq',$something_id);
                $UpdataWhere['genre']=array('eq',1);
                $SomeThingData=Something::get($something_id);
                if($SomeThingData->status>=2){
                    $Updata['is_find']=1;
                }else{
                    $Updata['is_find']=0;
                }
                $Updata['is_share']=1;



                $shareOne=$shareModel->where($UpdataWhere)->find();
                if(empty($shareOne)){

                    $dataParent['user_id']=$user->id;
                    $dataParent['parent_user_id']=0;
                    $dataParent['something_id']=$something_id;
                    $dataParent['total_user_id']=$user->id;
                    $dataParent['createtime']=time();
                    $dataParent['is_share']=1;
                    $dataParent['genre']=1;
                    if($SomeThingData->status>=2){
                        $dataParent['is_find']=1;
                    }else{
                        $dataParent['is_find']=0;
                    }
                    Db::name('share')->insert($dataParent);
                    $shareModel->where($UpdataWhere)->find();
                }
                else{
                    $shareModel->save($Updata,$UpdataWhere);
                }
                $this->success('请求成功');

            }
            //类型:1=失物招领,2=找人,3=找物
            $type=(int)$this->request->request('Type',2);

            //搜索类型:1=最新发布,2=距离最近
            $SearchType=(int)$this->request->request('SearchType',1);

            //城市
            $city=$this->request->request('city');


            //搜索内容
            $keysword=$this->request->request('keysword');

            //页码
            $page=$this->request->request('page',1);

            //一页加载条数
            $limit=$this->request->request('limit',10);

            if($SearchType==2){
                //经度114.03289881
                $longitude= $this->request->request('longitude',114.03289881);

                //纬度 22.64382712
                $latitude = $this->request->request('latitude', 22.64382712);
            }

            $where['something.status']=array('in',array(1,2));

            if(!empty($city)){
                $cityArea=Area::get(['name'=>$city]);
                $city=$cityArea->id;
                if($type==1||$type==3){
                    $where['something.city']=array('eq',$city);
                }

            }else{
                $city=0;
            }




            //查询条件
            if(!empty($type)){
                $where['type']=array('eq',$type);
            }

            if(!empty($keysword)){
                $where['content']=['like','%'.$keysword.'%'];
            }
            if($SearchType==2){
                $data=$somethingModel->nearby($where,$page,$limit,$longitude,$latitude,$city);
            }else{
                $data=$somethingModel->getListNew($where,$page,$limit,$city);
            }

            //判断数据是否为空
            if(!empty($data)){
                //判断是点击近距离
                if($SearchType==2){
                    foreach ($data as $key=>&$val){
                        if(!empty($longitude)&&!empty($latitude)){
                            if(!empty($val['longitude'])&&!empty($val['latitude'])){
                                //计算距离
                                $val['length'] = web_getDistance($longitude,$latitude,$val['longitude'],$val['latitude']);
                            }else{
                                $val['length']=0;
                            }
                        }else{
                            $val['length']=0;
                        }
                    }
                    $data=array_sort($data,'length',0);
                }
                //根据距离值进行倒序排序

            }else{
                $this->success('请求成功','',[]);
            }
            $user=$this->auth->getUser();
            foreach ($data as $key=>$val){
                $data[$key]['chat_url']=url('index/messageroom',
                    array(
//                            'chat_id'=>$val['id'],chat_url
                        'user_id'=>$user->id,
                        'reply_user_id'=>$val['publisherUserId'],
                        'something_id'=>$val['id'],
                    )
                );


            }

            $bannerWhere['status']='normal';
            $banner['banner']=Db::name('banner')
                ->where($bannerWhere)
                ->select();
            if(!empty($banner['banner'])){
                $banner['banner']=collection($banner['banner'])->toArray();
            }else{
                $banner['banner']=array();
            }
            $good=new AuctionGood();
            $banner['goods']=$good->getList(1,1,3);

            $this->success('请求成功','',$data,$banner);

        }

        $options=configNew();
        $app = new Application($options);

        $js = $app->js;
        $this->view->assign('js',$js);
        $this->view->engine->layout('layout/default');

        if($TypeName==1){
            $this->view->engine->layout('layout/default');
            return $this->view->fetch('lookfound');
        }elseif ($TypeName==2){
            $this->view->engine->layout('layout/default');
            return $this->view->fetch('lookpeople');
        }elseif ($TypeName==3){
            $this->view->engine->layout('layout/default');
            return $this->view->fetch('lookthing');

        }else{
            return $this->view->fetch();
        }

    }

    /**
     * 消息列表
     */
    public function messagelist(){
        if($this->request->isAjax()){
            $page=$this->request->post('page');
            $user=$this->auth->getUser();
            $charModel=new Chat();
            $where['chat.user_id|chat.reply_user_id']=array('eq',$user->id);
            $data=$charModel->getList($where,$page);
            if(empty($data)){
                $this->error('暂无数据','',[]);
            }
            $this->success('请求成功','',$data);

        }

        $this->view->engine->layout('layout/default');
        return $this->view->fetch();

    }

    /**
     * 消息聊天模式
     */
    public function messageroom(){
//        $chat_id=$this->request->param('chat_id');
        $reply_user_id=$this->request->param('reply_user_id');
        $something_id=$this->request->param('something_id');
        $chat_user_id=$this->request->param('user_id');

        $user=$this->auth->getUser();
        $where['user_id']=$chat_user_id;
        $where['something_id']=$something_id;
        $where['reply_user_id']=$reply_user_id;
        $charModel=new Chat();
        $number=$charModel->where($where)->find();

        if($this->request->isAjax()){
            $page=$this->request->post('page');
            $chat_id=$this->request->post('chat_id');
            $user=$this->auth->getUser();

            $chardetailModel=new ChatDetail();
            $where1t['chat_id']=$chat_id;
            $data=$chardetailModel->getList($where1t,$page);
            if(empty($data)){
                $this->error('暂无数据','',[]);
            }
            foreach ($data as $key=>$val){
                $data[$key]['time']=$val['createtime'];
                if($val['chat']['user_id']==$user->id){
                    if($val['user_id']==$user->id){
                        $data[$key]['type']='i';
                    }else{
                        $data[$key]['type']='you';
                    }

                }else{
                    if($val['user_id']==$user->id){
                        $data[$key]['type']='i';
                    }else{
                        $data[$key]['type']='you';
                    }
                }
                $data[$key]['avatar']=$val['user']['avatar'];
                $data[$key]['message']=$val['content'];

            }
            $this->success('请求成功','',$data);
        }

        if(empty($number)){

            $data['user_id']=$chat_user_id;
            $data['reply_user_id']=$reply_user_id;
            $data['something_id']=$something_id;
            $data['createtime']=time();

            $chat_id=$charModel->insertGetId($data);
        }else{
            $chat_id=$number->id;
        }
        $rUserModel=new \app\common\model\User();
        $something=Something::get($something_id);
        if($val['reply_user_id']=$something['publisherUserId']){
            $name=$something->contacts;
        }else{
            $name=$val['user']['nickname'];
        }
        $rUserData=$rUserModel->where(['id'=>array('eq',$reply_user_id)])->find();
        $this->view->assign('chat_id',$chat_id);
        $this->view->assign('name',$name);//$rUserData->nickname);
        $this->view->assign('reply_user_id',$reply_user_id);
        $this->view->assign('something_id',$something_id);
        $this->view->assign('chat_user_id',$chat_user_id);
        $this->view->assign('user_id',$user->id);
        $this->view->engine->layout('layout/default');
        return $this->view->fetch();
    }

    /**
     * 信息详情
     */
    public function detail(){
        $money=0;
        $id=$this->request->param('id');
        $parent_user_id=$this->request->param('parent_user_id');
        //分享进行一系列数据操作
        if(isset($parent_user_id)&&!empty($parent_user_id)){
           Session::set('share_user_id',$parent_user_id);
           try{
               Db::startTrans();
               $shareModel=new Share();
               $UpdataWhere['user_id']=array('eq',$parent_user_id);
               $UpdataWhere['something_id']=array('eq',$id);
               $UpdataWhere['genre']=array('eq',1);

               $SomeThingData=Something::get($id);
               if($SomeThingData->status>=2){
                   $Updata['is_find']=1;
               }else{
                   $Updata['is_find']=0;
               }
               $Updata['is_share']=1;

               $shareOne=$shareModel->where($UpdataWhere)->find();
               if(empty($shareOne)){

                   $dataParent['user_id']=$parent_user_id;
                   $dataParent['parent_user_id']=0;
                   $dataParent['something_id']=$id;
                   $dataParent['total_user_id']=$parent_user_id;
                   $dataParent['is_share']=1;
                   $dataParent['genre']=1;
                   if($SomeThingData->status>=2){
                       $dataParent['is_find']=1;
                   }else{
                       $dataParent['is_find']=0;
                   }
                   $dataParent['createtime']=time();
                   Db::name('share')->insert($dataParent);
                   $shareOne=$shareModel->where($UpdataWhere)->find();
               }
//               else{
//                   $shareModel->save($Updata,$UpdataWhere);
//               }

               $user=$this->auth->getUser();
               $data['user_id']=$user->id;
               $data['parent_user_id']=$parent_user_id;
               $data['something_id']=$id;
               $data['total_user_id']=$shareOne->total_user_id;
               $data['is_share']=0;
               $data['genre']=2;

               if($SomeThingData->status>=2){
                   $data['is_find']=1;
               }else{
                   $data['is_find']=0;
               }
               $data['createtime']=time();

               $UpdataWhereNew['user_id']=array('eq',$user->id);
               $UpdataWhereNew['something_id']=array('eq',$id);
               $UpdataWhereNew['genre']=array('eq',1);
               $shareOneNew=$shareModel->where($UpdataWhereNew)->find();
               if(empty($shareOneNew)){
                   Db::name('share')->insert($data);
               }

               Db::commit();
           }catch (\Exception $e){
               var_dump($e->getMessage());
                Db::rollback();
           }


        }
        $site=\think\Config::get('site');
        $id=$this->request->param('id');
        $detailData=Something::get($id);
        $detailOne=$detailData->toArray();
        if($detailOne['type']==1){
            $detailOne['label']='失物招领';
        }elseif ($detailOne['type']==2){
            $detailOne['label']='找人';
        }elseif ($detailOne['type']==3){
            $detailOne['label']='找物';
        }else{
            $detailOne['label']='';
        }
        $detailOne['user']=$detailData->user()->find()->toArray();

        $images=explode(',',$detailData['images']);
        if(is_array($images)){
            $detailOne['images']=$images;
        }
        $SomethingMOdel=new Something();
        $SomethingMOdel->where(['id'=>array('eq',$id)])->setInc('browse',1);
        if($detailOne['type']==2||$detailOne['type']==3){
            //分享可获得赏金
            if($site['share_profit']>0){
                if($site['share_profit']>100){
                    $money=($detailOne['money']*(100/100))/100;
                }else{
                    $money=($detailOne['money']*(1-$site['share_profit']/100))/100;
                }
            }else{
                $money=0;
            }
        }elseif ($detailOne['type']==1){
            //分享可获得报酬
            if($site['completed_revenue']>0){
                if($site['completed_revenue']>100){
                    $money=($detailOne['money']*(100/100))/100;
                }else{
                    $money=($detailOne['money']*(1-$site['completed_revenue']/100))/100;
                }
            }else{
                $money=0;
            }
        }

        $user_new=$this->auth->getUser();
        $chat_url=url('index/messageroom',
            array(
//                            'chat_id'=>$val['id'],chat_url
                'user_id'=>$user_new->id,
                'reply_user_id'=>$detailOne['publisherUserId'],
                'something_id'=>$detailOne['id'],
            )
        );


        $options=configNew();
        $app = new Application($options);

        $js = $app->js;
        $this->view->assign('js',$js);
        $this->view->assign('money',$money);

        $this->view->assign('something',$detailOne);
        $this->view->assign('images',$images);
        $this->view->assign('id',$id);
        if($detailOne['publisherUserId']==$user_new->id){
            $chat_url=1;
            $this->view->assign('chat_url',$chat_url);
        }else{
            $this->view->assign('chat_url',$chat_url);
        }


        $this->view->engine->layout('layout/default');
       return $this->view->fetch();

    }

    public function getShareLink(){
        $user=$this->auth->getUser();
        $something_id=$this->request->post('something_id');
        $parent_user_id=$user->id;
        $data=$this->auth->ShareLink($something_id,$parent_user_id);
        $this->success('请求成功','',$data);
    }

    /**
     * 回调地址
     */
    function oauth_callback(){

        $conf= configNew();
        $app = new Application($conf);
        $oauth = $app->oauth;
        $user = $oauth->user()->toArray();

        Session::set('wechat_user',$user);
        $targetUrl =empty(Session::get('target_url'))?'/index/index/index':Session::get('target_url');


        header('location:'. $targetUrl); // 跳转到
    }

    /**
     * 微信支付异步回调地址(找物/找人/失物招领)
     */
    public function notify(){

        $wxConf =configNew();
        $wxApp = new Application($wxConf);
        $response = $wxApp->payment->handleNotify(function ($notify,$successful){
            if($successful){
                $order=Db::name('something')
                    ->where(['partner_trade_no'=>array('eq',$notify->out_trade_no)])
                    ->find();
                if(!empty($order)){
                    if($order['type']!=1){
                        if($order['status']==0){
                            $data['status']=1;
                        }

                    }else{
                        if($order['status']<3&&!empty($order['receiverUserId'])){
                            $data['status']=2;
                            if($order['status']>0){
                                $wechat =new Wechat();
                                $user=\app\admin\model\User::get($order['receiverUserId']);
                                $templateData['keyword1']=randSole(5,6);
                                $templateData['keyword2']=$order['content'];
                                $templateData['keyword3']=$user->nickname;
                                $receiverUser=\app\common\model\User::get($order['publisherUserId']);
                                $templateData['keyword4']=$receiverUser->nickname;
                                $templateData['remark']='请及时处理';
                                try{
                                    $tempStatus= $wechat
                                        ->template('ra11Lhawrk3tG79AILUkzW1EjBH6FE-YV9zUfwimbMg',url('user/mypublish',
                                            array(),true,true),$templateData,
                                            $receiverUser->openid);
                                }catch (\Exception $e){

                                }
                            }

                        }

                    }

                   try{
                       Db::startTrans();
                       Db::name('something') ->where(['partner_trade_no'=>array('eq',$notify->out_trade_no)])->update($data);
                       Db::commit();
                   }catch (\Exception $e){
                       Db::rollback();
                        return false;
                   }
                    return true;
                }
            }else{
                return false;
            }
        });
        return $response;

    }

    /**
     * 微信支付回调地址(开通vip)
     */
    public function vipnotify(){
        $wxConf =configNew();
        $wxApp = new Application($wxConf);
        $response = $wxApp->payment->handleNotify(function ($notify,$successful){
            if($successful){
                $order=Db::name('user')
                    ->where(['order_sn'=>array('eq',$notify->out_trade_no)])
                    ->count();
                if(!empty($order)){
                    $data['is_vip']=1;
                    try{
                        Db::startTrans();
                        Db::name('user') ->where(['order_sn'=>array('eq',$notify->out_trade_no)])->update($data);
                        Db::commit();
                    }catch (\Exception $e){
                        Db::rollback();
                        return false;
                    }
                    return true;
                }
            }else{
                return false;
            }
        });
        return $response;
    }

    /**
     * 竞拍首页
     */
    public function auction(){
        $auctionBanner=new AuctionBanner();
        $category=new AuctionCategory();
        $good=new AuctionGood();
        if($this->request->isAjax()){
            $bannerWhere['status']=array('eq','normal');
            $page=$this->request->post('page',1);
            $category_id=$this->request->post('category_id');
            $data['banner']=collection($auctionBanner->getList($bannerWhere,1,100))->toArray();
            $data['category']=collection($category->getList(1,1,100))->toArray();
            if(!empty($category_id)){
                $goodWhere['category_id']=array('eq',$category_id);
            }
            $goodWhere['status']=array('eq',1);

            $data['list']=collection($good->getList($goodWhere,$page,10))->toArray();

            $this->success('请求成功','',$data);

        }

        return $this->view->fetch();
    }

    /**
     * 竞拍详情
     */
    public function auctiondetail(){
        $good=new AuctionGood();
        $order=new AuctionOrder();
        $user=$this->auth->getUser();
        $user_id=$user->id;
        $id=$this->request->param('id');
        $parent_user_id=$this->request->param('parent_user_id');
        if(isset($parent_user_id)&&!empty($parent_user_id)){
            Session::set('share_user_id',$parent_user_id);
            try{
                Db::startTrans();
                $shareModel=new Share();
                $UpdataWhere['user_id']=array('eq',$parent_user_id);
                $UpdataWhere['something_id']=array('eq',$id);
                $UpdataWhere['genre']=array('eq',2);

                $goods=\app\common\model\AuctionGood::get($id);
                if($goods->status>=2){
                    $Updata['is_find']=1;
                }else{
                    $Updata['is_find']=0;
                }
                $Updata['is_share']=1;

                $shareOne=$shareModel->where($UpdataWhere)->find();
                if(empty($shareOne)){

                    $dataParent['user_id']=$parent_user_id;
                    $dataParent['parent_user_id']=0;
                    $dataParent['something_id']=$id;
                    $dataParent['total_user_id']=$parent_user_id;
                    $dataParent['is_share']=1;
                    $dataParent['genre']=2;
                    if($goods->status>=2){
                        $dataParent['is_find']=1;
                    }else{
                        $dataParent['is_find']=0;
                    }
                    $dataParent['createtime']=time();
                    Db::name('share')->insert($dataParent);
                    $shareOne=$shareModel->where($UpdataWhere)->find();
                }
                $user=$this->auth->getUser();
                $data['user_id']=$user->id;
                $data['parent_user_id']=$parent_user_id;
                $data['something_id']=$id;
                $data['total_user_id']=$shareOne->total_user_id;
                $data['is_share']=0;
                $data['genre']=2;

                if($goods->status>=2){
                    $data['is_find']=1;
                }else{
                    $data['is_find']=0;
                }
                $data['createtime']=time();

                $UpdataWhereNew['user_id']=array('eq',$user->id);
                $UpdataWhereNew['something_id']=array('eq',$id);
                $UpdataWhereNew['genre']=array('eq',2);
                $shareOneNew=$shareModel->where($UpdataWhereNew)->find();
                if(empty($shareOneNew)){
                    Db::name('share')->insert($data);
                }

                Db::commit();
            }catch (\Exception $e){
                var_dump($e->getMessage());
                Db::rollback();
            }


        }

        if($this->request->isAjax()){
            $id=$this->request->post('id');

            $detialWhere['id']=array('eq',$id);
            $data['detail']=$good->find($detialWhere);

            $orderWhere['good_id']=array('eq',$id);
            $data['order']=collection($order->getListNew($orderWhere,1,10))->toArray();

            $where['good_id']=array('eq',$data['detail']->id);
            $where['user_id']=array('eq',$user_id);
            $data['myPrice']=$order->getPrice($where);

            $data['ordercount']=$order->count();

            $options=configNew();
            $app = new Application($options);

            $js = $app->js;
            $data['js']=$js->config(array('chooseWXPay'),$debug = false, $beta = false, $json = false);

            $this->success('请求成功','',$data);
        }


        return $this->view->fetch();
    }

    /**
     * 获取当前最新价格
     */
    public function getPrice(){
        $id=$this->request->post('id');

        $good=new AuctionGood();
        $where['id']=array('eq',$id);
        $goodArray=$good->find($where);
        if(!empty($goodArray)){
            $data['price']=$goodArray->money;
        }else{
            $data['price']=0;
        }
        $this->success('请求成功','',$data);

    }

    /**
     * 获取当前是否有用户超过出价
     */
    public function getOne(){
        $id=$this->request->post('id');
        $user=$this->auth->getUser();
        $user_id=$user->id;
        $order=new AuctionOrder();
        $where['good_id']=array('eq',$id);
        $orderArray=$order->findOne($where);
        if(!empty($orderArray)){
            if($orderArray->user_id!=$user_id){
                $data['string']='您有一件商品被超价了,赶紧去竞价吧';
            }
        }else{
            $data['string']='';
        }
        $this->success('请求成功','',$data);

    }




    /**
     * 竞拍记录(我的竞拍记录/全部竞拍记录)
     */
    public function record(){
        $order=new AuctionOrder();
        $good=new AuctionGood();
        $user=$this->auth->getUser();
        $user_id=$user->id;
        if($this->request->isAjax()){
            $id=$this->request->post('id');
            $detialWhere['id']=array('eq',$id);
            $detail=$good->find($detialWhere);
            $name=$this->request->post('name');
            $page=$this->request->post('page',1);
            $good_id=$this->request->post('good_id');
            $limit=$this->request->post('limit',10);
            $where['good_id']=array('eq',$good_id);
            if($name=='all'){
                $data=$order->getListNew($where,$page,$limit);
            }elseif ($name=='my'){
                $where['user_id']=array('eq',$user_id);
                $data=$order->getListNew($where,$page,$limit,$detail->receiverUserId);
            }
            $this->success('请求成功','',$data);
        }
        return $this->view->fetch();
    }

    /**
     * 发布竞拍
     */
    public function publishgood(){
        $user=$this->auth->getUser();
        $good=new AuctionGood();
        $category=new AuctionCategory();
        $user_id=87;//$user->id;
        if($this->request->isAjax()){

            $data['name']=$this->request->post('name');
            $data['desc']=$this->request->post('desc');
            $data['images']=$this->request->post('images');
            $data['publisherUserId']=$user_id;
            $data['range']=$this->request->post('range');
            $data['price']=$this->request->post('price');
            $data['category_id']=$this->request->post('category_id');
            $data['hour']=72;
            $data['contacts']=$this->request->post('contacts');
            $data['telephone']=$this->request->post('telephone');
            $data['status']=1;
            $data['createtime']=time();
            $validate =  Loader::validate('AuctionGood');
            if($validate->check($data)){
                $data=$good->add($data);
            }else{
                $this->error($validate->getError());
            }


            $this->success('请求成功','',$data);

        }
        return $this->view->fetch();
    }

    /**
     * 我发布的竞拍商品
     */
    public function mypublishgood(){
        $user=$this->auth->getUser();
        $good=new AuctionGood();
        $user_id=$user->id;

        if($this->request->isAjax()){
            $where['publisherUserId']=array('eq',$user_id);
            $page=$this->request->post('page',1);
            $limit=$this->request->post('limit',10);
            $data=collection($good->goodList($where,$page,$limit))->toArray();
            $this->success('请求成功','',$data);
        }
        return $this->view->fetch();
    }

    /**
     * 我参与的竞拍商品
     */
    public function participategood(){
        $user=$this->auth->getUser();
        $user_id=$user->id;
        $order=new AuctionOrder();
        $good=new AuctionGood();
        if($this->request->isAjax()){
            $page=$this->request->post('page',1);
            $limt=$this->request->post('limit',10);
            $map['user_id']=array('eq',$user_id);
            $goodIds=$order->filed($map,'good_id');

            if(!empty($goodIds)){
                $goodIds=array_unique($goodIds);
                $where['id']=array('in',$goodIds);

                $data=collection($good->participategood($where,$page,$limt,$user_id))->toArray();

            }else{

                $data=[];
            }

            $this->success('请求成功','',$data);
        }
        return $this->view->fetch();
    }



    /**
     * 竞拍分享
     */
    public function shareauction(){
        $user=$this->auth->getUser();

        $parent_user_id=$user->id;
        $name=$this->request->post('name');
        $id=$this->request->post('id');
        if($name=='get'){
            $data=$this->auth->ShareAuctionLink($id,$parent_user_id);
        }elseif($name=='share'){
            $user=$this->auth->getUser();
            $shareModel=new Share();
            $UpdataWhere['user_id']=array('eq',$parent_user_id);
            $UpdataWhere['something_id']=array('eq',$id);
            $UpdataWhere['genre']=array('eq',2);
            $good=\app\common\model\AuctionGood::get($id);
            if($good->status>=2){
                $Updata['is_find']=1;
            }else{
                $Updata['is_find']=0;
            }
            $Updata['is_share']=1;



            $shareOne=$shareModel->where($UpdataWhere)->find();
            if(empty($shareOne)){
                $dataParent['user_id']=$parent_user_id;
                $dataParent['parent_user_id']=0;
                $dataParent['something_id']=$id;
                $dataParent['total_user_id']=$parent_user_id;
                $dataParent['createtime']=time();
                $dataParent['is_share']=1;
                $dataParent['genre']=2;
                if($good->status>=2){
                    $dataParent['is_find']=1;
                }else{
                    $dataParent['is_find']=0;
                }
                Db::name('share')->insert($dataParent);
                $shareModel->where($UpdataWhere)->find();
                $data=[];
            }
            else{
                $data=$shareModel->save($Updata,$UpdataWhere);
            }
        }

        $this->success('请求成功','',$data);
    }

    /**
     * 确认收货和确认发货
     */
    public function logistics(){
        $name=$this->request->post('request_name');
        $id=$this->request->post('id');
        $data=array('code'=>0,'msg'=>'请求失败');
        try{
            $good=\app\common\model\AuctionGood::get($id);

            if($good->status==2){
                if($name=='deliver'){
                    //确认发货
                    $good->send=1;
                }elseif ($name=='receiving'){
                    //确认收货
                    $good->send=2;
                }

                $good->save();
                $data['code']=1;
                $data['msg']='请求成功';
            }

        }catch (\Exception $e){

        }

        return json($data);


    }

    /**
     * 微信支付回调地址(竞拍)
     */
    public function  bidnotify(){
        $wxConf =configNew();

        $wxApp = new Application($wxConf);
        $response = $wxApp->payment->handleNotify(function ($notify,$successful){
            if($successful){
                $orderLog=new OrderLog();
                $order=Db::name('auction_order_tem')
                    ->where(['order_sn'=>array('eq',$notify->out_trade_no)])
                    ->find();
                if(!empty($order)){

                    $data['status']=2;
                    try{
                        Db::startTrans();

                        $goods=\app\common\model\AuctionGood::get($order['good_id']);

                        $goods->money= $order['price'];
                        $goods->save();

                        Db::name('auction_order_tem') ->where(['order_sn'=>array('eq',$notify->out_trade_no)])->update($data);
                        $adata['user_id']=$order['user_id'];
                        $adata['good_id']=$order['good_id'];
                        $adata['order_sn']=$order['order_sn'];
                        $adata['money']=$order['money'];
                        $adata['createtime']=$order['createtime'];
                        $adata['price']=$order['price'];

                        $where['user_id']=array('eq',$order['user_id']);
                        $where['good_id']=array('eq',$order['good_id']);

                        $orderSave=$orderLog->where($where)->find();
                        if(!empty($orderSave)){
                            $orderSave->order_sn=$order['order_sn'];
                            $orderSave->money=$order['money'];
                            $orderSave->price=$order['price'];
                            $orderSave->createtime=$order['createtime'];
                            $orderSave->save();
                        }else{
                            $data_order['user_id']=$order['user_id'];
                            $data_order['good_id']=$order['good_id'];
                            $data_order['order_sn']=$order['order_sn'];
                            $data_order['money']=$order['money'];
                            $data_order['status']=2;
                            $data_order['createtime']=$order['createtime'];
                            $data_order['price']=$order['price'];
                            $data_order['price']=$order['price'];
                            $orderLog->save($data_order);
                        }

                        Db::name('auction_order')->insert($adata);
                        Db::commit();
                    }catch (\Exception $e){
                        Db::rollback();
                        return false;
                    }




                    $wechat =new Wechat();
                    $whereGood['good_id']=array('eq',$order['good_id']);
                    $orderLogCout=$orderLog->where($whereGood)->count();
                    if($orderLogCout>=2){
                        $orderLogArray=$orderLog->where($whereGood)->order('createtime desc')->page(1)->limit(2)->select();
                        if(!empty($orderLogArray)){
                            $orderLogArray=collection($orderLogArray)->toArray();
                            $log=$orderLogArray[1];
                            $goodWhere['id']=array('eq',$order['good_id']);
                            $good=Db::name('auction_good')->where($goodWhere)->find();
                            $user=\app\admin\model\User::get($log['user_id']);
                            $templateData['keyword1']='正在竞拍 '.$good['name'];
                            $templateData['keyword2']=$good['money'];
                            $templateData['remark']='立即前往加价';
                            try{
                                $wechat->template('RgXE4-4V9yB04-BiJpzMKIppY0cSXdtOIkdMs4AIORg',
                                    url('index/auctiondetail',array('id'=>$order['good_id']),true,true),$templateData,$user->openid);
                            }catch (\Exception $e){

                            }
                        }

                    }




                    return true;
                }
            }else{
                return false;
            }
        });
        return $response;
    }








}
